const router = require('koa-router')()
const UserHelp =require('../database/users/userHelp')
const msgHelp =require('../database/msgs/msgHelp')
const UnReadMsgHelp =require('../database/unread/UnReadMsgHelp')
const CountsHelp=require('../database/count/CountsHelp')




//供管理员用来出测试的接口
router.post('/api/admin/removeUser', async (ctx, next) => {
    let uid=ctx.request.body.uid-0

    let data= await UserHelp.removeUser(uid)
    ctx.body={
        code:0,
        data:data
    }
})



router.post('/api/admin/changeSysName',async (ctx, next) => {
    let username=ctx.request.body.username
    let uid=ctx.request.body.uid

    let data= await UserHelp.changeSysName(uid,username)
    ctx.body={
        code:0,
        data:data
    }
})




router.post('/api/saveSysUser', async (ctx, next) => {

    let {uid,name,username}=ctx.request.body
    let user={
        uid,
        name,
        username
    }
    let data= await UserHelp.saveUser(user)

    ctx.body={
        code:0,
        data:data
    }
})




//编写unreadmsg接口时做的调试
router.post('/api/test/saveUnread',async (ctx, next) => {

    let {to_uid,from_uid,mid}=ctx.request.body
    to_uid=to_uid-0
    from_uid=from_uid-0
    mid=mid-0


    let msg=await UnReadMsgHelp.getUnReadMsg(to_uid)

    if(!msg){
        let  msg_ids={}
        msg_ids[from_uid-0]=[mid]       //对于群而言是gid
        let obj={
            to_uid:to_uid,
            msg_ids:msg_ids,
        }
        UnReadMsgHelp.saveUnReadMsg(obj)

    }
    else{  //更新
        let msg_ids=msg.msg_ids

        if(msg_ids[from_uid]){
            msg_ids[from_uid].push(mid)
        }
        else{
            msg_ids[from_uid]=[mid]
        }

        let unRead=msg.unRead-0

        let obj={
            to_uid:to_uid,
            msg_ids:msg_ids,
            unRead:unRead+1
        }

        UnReadMsgHelp.updateUnReadMsg(obj,to_uid)
    }

    ctx.body={
        code:0,
        data:''
    }

})



//编写count接口时做的调试
router.get('/api/test/saveCount', async (ctx, next) => {
    let {from_uid}=ctx.request.query
    CountsHelp.updateCounts(from_uid)
    ctx.body={
        code:0,
        data:""
    }
})


//编写count接口时做的调试
router.get('/api/test/getCount', async (ctx, next) => {

    let res=await CountsHelp.getCounts()

    let total_num=0
    if(res){
        total_num=res.total_num
    }

    ctx.body={
        code:0,
        data:{
            total_num,
        }
    }
})




//手动读掉某条消息
router.get('/api/admin/readMsgByUid', async (ctx, next) => {

    let {uid,myuid}=ctx.request.query

    await msgHelp.readMsg(uid-0,myuid-0)

    ctx.body={
        code:0,
        data:""
    }
})







module.exports = router